<?php

class NewsController extends Controller
{
	/**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   public function actionIndex()
	{
		
      $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 'news_date_create'; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'DESC'; // Lấy giá trị muốn sắp xếp
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);  
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;  
      $list = array();
      $model = new News();
      $model->unsetAttributes();
      
      $criteria = new CDbCriteria;
      $criteria->limit = $limit;
      $criteria->offset = $start;
      $criteria->order = $sidx . ' ' . $sord;
      if(isset($_POST['News'])){ // Nếu người dùng search
         $model->attributes = $_POST['News'];
         $params = array();
         
         if(isset($_POST['start_date'])){
            $criteria->addCondition("news_date_create >= :start_date", "AND");
            $params[':start_date'] = strtotime(str_replace('/','-',$_POST['start_date']));
         }
         if(isset($_POST['end_date'])){
            $criteria->addCondition("news_date_create <= :end_date", "AND");
            $params[':end_date'] = strtotime(str_replace('/','-',$_POST['end_date'])) + 86400; //Cuối ngày
         }
         if($model->news_title != ''){
            $criteria->addCondition("news_title like :news_title", "AND");
            $params[':news_title'] = '%'.$model->news_title.'%';
         }
         $criteria->params = $params;
         //CVarDumper::dump($criteria->params,10,true);die();
         $object = $model->findAll($criteria);
      }else{
         $object = $model->findAll($criteria);   
      }
      //CVarDumper::dump($object,10,true);die();
      if(count($object) > 0){
         foreach($object as $item){
            $list[$item->attributes['news_id']] = $item->attributes;
         }
      }
      //CVarDumper::dump($list,10,true);die();
      $total_record = $model->count($criteria); // Đếm tổng số bản ghi
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      
      $this->render('index',array("model" => $model,
                                  "session_user" => $session_user,
                                  "list" => $list,
                                  "rowList" => $rowList,
                                  "page" => $page,
                                  "start" => $start,
                                  "limit" => $limit,
                                  "total_record" => $total_record,
                                  "total_pages" => $total_pages,
                                  ));
	}
   
   /**
    * 
    * Display page create
   */
   public function actionCreate(){
      $model = new News();
      $PostImage = new PostImage();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['News'])){
         $model->attributes = $_POST['News'];
         $model->news_date_create = time();
         if($model->validate()){
            if($model->save()){
               $message = "Đăng tin thành công";   
               
               //Upload image
               $images = CUploadedFile::getInstancesByName('News');
               if(isset($images) && count($images)> 0)
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/news/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){    
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $news = News::Model()->findByPk($model->news_id);
                           $news->news_image = $fileName;
                           $news->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(140);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);               
                     }                
                  }
               }
            }
            
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      $this->pageTitle = 'Đăng tin tức';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array('model'=>$model,
                                    'PostImage' => $PostImage,
                                    'session_user' => $session_user,
                                    'message' => $message));
   }
   
   /**
    * 
    * Display page edit
   */
   public function actionEdit($id){
      $model =  News::model()->findByPk($id);
      $PostImage = new PostImage();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['News'])){
         $model->attributes = $_POST['News'];
         $model->news_date_create = time();
         if($model->validate()){
            if($model->save()){
               $message = "Cập nhật thành công";   
               
               //Upload image
               $images = CUploadedFile::getInstancesByName('News');
               if(isset($images) && count($images)> 0)
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/news/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){    
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $news = News::Model()->findByPk($model->news_id);
                           $news->news_image = $fileName;
                           $news->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(140);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);               
                     }                
                  }
               }
            }
            
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      
      
      $this->pageTitle = 'Cập nhật tin tức';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array('model'=>$model,
                                    'PostImage' => $PostImage,
                                    'session_user' => $session_user,
                                    'message' => $message));
   }
   
   

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}